package cn.edu.usst.cs.goldfish.booking.meetingroom.web.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
import cn.edu.usst.cs.goldfish.booking.meetingroom.model.MeetingAttendee;
import cn.edu.usst.cs.goldfish.booking.meetingroom.model.Meeting;
import cn.edu.usst.cs.goldfish.booking.meetingroom.model.MeetingRoom;
import cn.edu.usst.cs.goldfish.booking.meetingroom.mybatis.MeetingAttendeeMapper;
import cn.edu.usst.cs.goldfish.booking.meetingroom.mybatis.MeetingMapper;
import cn.edu.usst.cs.goldfish.booking.meetingroom.mybatis.MeetingRoomMapper;
import cn.edu.usst.cs.goldfish.booking.meetingroom.model.SysUser;
import cn.edu.usst.cs.goldfish.booking.meetingroom.mybatis.UserMapper;
import cn.edu.usst.cs.goldfish.booking.meetingroom.handler.GoldfishBookingException;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Slf4j
@RestController
@RequestMapping("/api/attend")
public class MeetingAttendeeController {
    @Autowired
    private MeetingAttendeeMapper meetingAttendeeMapper;
    @Autowired
    private MeetingMapper meetingMapper;
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/join")
    public synchronized String joinMeeting(@RequestParam Long meetingId, @SessionAttribute("email") String email) {
        log.info("参会请求 - meetingId: {}, email: {}", meetingId, email);
        
        if (email == null) {
            log.warn("用户未登录或email未设置");
            throw new GoldfishBookingException("未登录");
        }
        
        // 根据email查询用户ID
        SysUser user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("email", email));
        if (user == null) {
            log.warn("根据email未找到用户: {}", email);
            throw new GoldfishBookingException("用户不存在");
        }
        
        Long userId = user.getId();
        log.info("根据email查询到的userId: {}", userId);
        Meeting meeting = meetingMapper.selectById(meetingId);
        if (meeting == null) {
            throw new GoldfishBookingException("会议不存在");
        }
        // 主持人不能重复参会
        if (userId.equals(meeting.getOrganizerId())) {
            throw new GoldfishBookingException("主持人无需重复参会");
        }
        // 校验是否已参会
        List<MeetingAttendee> attendees = meetingAttendeeMapper.selectByMeetingId(meetingId);
        boolean alreadyJoined = attendees.stream().anyMatch(a -> a.getUserId().equals(userId));
        if (alreadyJoined) {
            throw new GoldfishBookingException("已参会，无需重复加入");
        }
        // 校验人数
        MeetingRoom room = meetingRoomMapper.selectById(meeting.getRoomId());
        int max = room.getCapacity() == null ? 0 : room.getCapacity();
        int current = attendees.size() + 1; // +1为主持人
        if (current >= max) {
            throw new GoldfishBookingException("会议已满员");
        }
        // 插入参会记录
        MeetingAttendee attendee = new MeetingAttendee();
        attendee.setMeetingId(meetingId);
        attendee.setUserId(userId);
        attendee.setJoinedAt(LocalDateTime.now());
        meetingAttendeeMapper.insert(attendee);
        return "参会成功";
    }
} 